/**
 * Created by wangjian on 2017/5/15.
 */
$(function () {

    var self = this;
    window.web_flag = 'liyu_crane';
    window.config = {
        gate_host: '192.168.1.191:5006',
        host: '192.168.1.191:5006',
        username: 'liyu_crane_client',
        password: 'liyu_crane_client',
        device_id: 'web',
        client_type: 'pc'
    };

    var client;
    var request_callback_map = {};
    var state_defered_array = [];
    var state = 0;//0:未登录 1:已登录 -1:错误
    var callid = 0;


    function cleanup() {
        if (client) {
            client.onMessageArrived = function () {

            };
            client.onConnectionLost = function () {

            };
            client.onMessageDelivered = function () {

            };
            try {
                client.disconnect();
            } catch (Error) {

            }

            client = null;
        }
        request_callback_map = {};
        state = 0;
    }

    function handle_event(event_type, object) {
        console.log(event_type);
        console.log(object);

    }

    function handle_request(callback_id, object) {
        var cb = request_callback_map[callback_id];
        if (cb) {
            delete request_callback_map[callback_id];
            cb(object);
        }
    }


    function onConnect(args) {
        console.log("mqtt connect");
        console.log(args);
        state = 1;
        client.subscribe('crane_status/#', {qos: 1});

    }

    function onFailureLogin(args) {
        console.log("mqtt connect failure");
        console.log(args);
        gateway_login(window.config.username, window.config.password);
    }

    function onFailureGateWayLogin(args) {
        console.log("mqtt connect failure gateway");
        console.log(args);
        login(window.config.username, window.config.password)

    }

    function onConnectionLost(args) {
        console.log("onConnectionLost");
        console.log(args);
        if (args.errorCode == 8 || args.errorCode == 7) {
            login(window.config.username, window.config.password);
        }
    }

    function onMessageDelivered(args) {
        console.log("onMessageDelivered");
        console.log(args);
    }

    function trace(args) {
        console.log("trace");
        console.log(args);
    }

    function onMessageArrived(msg) {
        var topic = msg.destinationName;

        if (topic.indexOf(window.config.event_prefix) === 0) {
            var event_name = topic.replace(window.config.event_prefix, '');
            handle_event(event_name, JSON.parse(msg.payloadString));
        } else if (topic.indexOf(window.config.request_prefix) === 0) {
            var callid = topic.replace(window.config.request_prefix, '');
            handle_request(callid, JSON.parse(msg.payloadString));
        } else if (topic.indexOf('channel/') === 0) {
            var topic_arr = topic.split('/');

            handle_event(topic_arr[3], JSON.parse(msg.payloadString));

        }
        else if (topic.indexOf('group/') === 0) {

            var message = JSON.parse(msg.payloadString);
            console.log('--group', topic, message);
            if (message.type === 'event') {
                handle_event('group', message.obj);
            }
            else if (message.type === 'chat') {
                handle_chat(message.obj);
            }
            else if (message.type === 'chat_session') {
                handle_chat_session(message.obj);
            }
        }
        else if (topic.indexOf('realphone') === 0) {

            var message = JSON.parse(msg.payloadString);
            console.log('--realphone', topic, message);
            if (message.type === 'event') {
                handle_event('realphone', message.obj);
            }
        }
        else if (topic.indexOf(window.config.file_prefix) === 0) {

            var callid = topic.replace(window.config.file_prefix, '');
            handle_request(callid, msg.payloadBytes);
        }
        else if (topic.indexOf(window.config.file_response_prefix) === 0) {

            var callid = topic.replace(window.config.file_response_prefix, '');
            handle_request(callid, msg.payloadBytes);
        }


    }

    function init() {
        window.config.event_prefix = 'user/' + window.config.clientId + '/event/';
        window.config.request_prefix = 'user/' + window.config.clientId + '/web_api_response/';
        window.config.file_prefix = 'user/' + window.config.clientId + '/file_get_result/';
        window.config.file_response_prefix = 'user/' + window.config.clientId + '/file_send_response/';

        client.onMessageArrived = onMessageArrived;
        client.onConnectionLost = onConnectionLost;
        client.onMessageDelivered = onMessageDelivered;
    }

    function is_mqttserver() {
        if (window.config.mqtt_server_type == 'mqttserver') {
            return true;
        } else {
            return false;
        }
    }

    function login(username, password) {
        cleanup();
        window.config.mqtt_server_type = 'mqttserver';
        window.config.username = username;
        window.config.password = password;
        window.config.clientId = window.config.username + '@' + window.config.client_type + "@" + window.config.device_id;

        client = new Paho.MQTT.Client(window.config.host.split(':')[0], parseInt(window.config.host.split(':')[1]), window.config.clientId);
        init();
        client.connect({
            onSuccess: onConnect,
            onFailure: onFailureLogin,
            userName: window.config.username,
            password: window.config.password
        });
    }


    function gateway_login(username, password) {
        cleanup();
        window.config.mqtt_server_type = 'gateway';
        window.config.username = username;
        window.config.password = password;
        window.config.clientId = window.config.username + '@' + window.config.client_type + "@" + window.config.device_id;

        client = new Paho.MQTT.Client(window.config.gate_host.split(':')[0], parseInt(window.config.gate_host.split(':')[1]), window.config.clientId);
        init();
        client.connect({
            onSuccess: onConnect,
            onFailure: onFailureGateWayLogin,
            userName: window.config.username,
            password: window.config.password
        });


    }

    function ready(cb) {
        if (state === 1) {
            cb(true);
        }
        else if (state === -1) {
            cb(false);
        }
        else {
            var defered = $q.defer();
            state_defered_array.push(defered);
            defered.promise.then(function () {
                cb(true);
            }, function () {
                cb(false);
            })
        }
    }

    function logout() {
        cleanup();
    }

    function request(route, parms, cb) {
        if (client && client.isConnected()) {
            var callback_id = null;
            if (cb) {
                callback_id = window.config.client_type + "_" + window.config.username + "_" + callid++;
                if (callid > 999999) {
                    callid = 0;
                }
            }
            var payload = {
                callid: callback_id,
                route: route,
                parms: parms
            };
            if (cb) {
                request_callback_map[callback_id] = cb;
            }
            client.send("request/" + window.config.user_id, JSON.stringify(payload), 1, false);
        }
    }

    function liyu_web_api(web_flag, route, parms, cb, num) {
        if (client && client.isConnected()) {
            var callback_id = null;
            if (cb) {
                callback_id = window.config.client_type + "_" + window.config.username + "_" + callid++;
                if (callid > 999999) {
                    callid = 0;
                }
            }
            var payload = {
                callid: callback_id,
                web_flag: web_flag,
                route: route,
                parms: parms
            };
            if (cb) {
                request_callback_map[callback_id] = cb;
            }
            client.send("web_api_request/", JSON.stringify(payload), 1, false);
        } else {

            if (isNaN(num) || num < 4) {
                setTimeout(function () {
                    if (isNaN(num)) {
                        liyu_web_api(web_flag, route, parms, cb, 2);
                    } else {
                        num++;
                        liyu_web_api(web_flag, route, parms, cb, num);
                    }

                }, 2000);
            } else {
                cb(null, {status: 500, message: '网络不通畅,请稍后重试.'});
            }
        }
    }

    /*
     var send_user_message={
     target_type: 0, //目标类型 0:单聊 1:群聊
     target: 1, //目标id
     ctype: 'txt', //消息类型:txt:文字消息；file：附件消息；location：地理位置消息；vcard：名片消息；href：超链接消息；oa：oa消息;
     content: 'json', //内容
     ext: 'json', //扩展字段
     id_client: 1, //客户端提供的id
     push_content: '', //推送通知时显示的内容
     push_payload: 'json', //推送通知时显示的自定义字段
     is_push: 1, //是否推送
     is_unreadable: 1 //是否计入未读数
     }
     */
    function send_text_message_to_person(fname, target, text, ext) {
        var message = {
            fname: fname,
            target_type: 0, //目标类型 0:单聊 1:群聊
            target: target, //目标id
            ctype: 'txt', //消息类型:txt:文字消息；file：附件消息；location：地理位置消息；vcard：名片消息；href：超链接消息；oa：oa消息;
            content: {
                text: text
            }, //内容
            ext: ext, //扩展字段
            id_client: (new Date()).valueOf(), //客户端提供的id
            push_content: text, //推送通知时显示的内容
            push_payload: ext, //推送通知时显示的自定义字段
            is_push: true, //是否推送
            is_unreadable: true //是否计入未读数
        };
        request('send_message', message);
        return message;
    }

    function send_text_message_to_group(fname, target, text, ext) {
        var message = {
            fname: fname,
            target_type: 1, //目标类型 0:单聊 1:群聊
            target: target, //目标id
            ctype: 'txt', //消息类型:txt:文字消息；file：附件消息；location：地理位置消息；vcard：名片消息；href：超链接消息；oa：oa消息;
            content: {
                text: text
            }, //内容
            ext: ext, //扩展字段
            id_client: (new Date()).valueOf(), //客户端提供的id
            push_content: text, //推送通知时显示的内容
            push_payload: ext, //推送通知时显示的自定义字段
            is_push: true, //是否推送
            is_unreadable: true //是否计入未读数
        };
        request('send_message', message);
        return message;
    }

    function send_apdu_command_message_to_group(fname, target, text, ext) {
        var message = {
            fname: fname,
            target_type: 1, //目标类型 0:单聊 1:群聊
            target: target, //目标id
            ctype: 'apdu', //消息类型:txt:文字消息；file：附件消息；location：地理位置消息；vcard：名片消息；href：超链接消息；oa：oa消息;
            content: {
                text: text
            }, //内容
            ext: ext, //扩展字段
            id_client: (new Date()).valueOf(), //客户端提供的id
            push_content: null, //推送通知时显示的内容
            push_payload: null, //推送通知时显示的自定义字段
            is_push: false, //是否推送
            is_unreadable: false //是否计入未读数
        };
        request('send_message', message);
        return message;
    }

    function get_chat_session() {
        var defered = $q.defer();
        request('get_chat_session', {}, function (list) {
            defered.resolve(list);
        });
        return defered.promise;
    }

    function set_chat_session_read_time(session_id, time) {
        request('set_chat_session_read_time', {session_id: session_id, time: time});
    }

    function get_chat_history_person(target, last_time) {
        var defered = $q.defer();
        request('get_chat_history', {
            target: target,
            target_type: 0,
            last_time: last_time
        }, function (result) {
            defered.resolve(result);
        });
        return defered.promise;
    }

    function get_chat_history_group(target, last_time) {
        var defered = $q.defer();
        request('get_chat_history', {
            target: target,
            target_type: 1,
            last_time: last_time
        }, function (result) {
            defered.resolve(result);
        });
        return defered.promise;
    }

    function delete_chat_session(target, target_type) {
        request('delete_chat_session', {target: target, target_type: target_type});
    }

    function realphone() {
        // client.subscribe('realphone',{qos:1});

        client.send("realphone", JSON.stringify({}), {qos: 1, retain: false});
    }


    function opc_event_publish_test(route, parms, web_flag) {
        if (client && client.isConnected()) {
            if (!web_flag) {
                web_flag = localStorage.get("web_flag");
            }
            var payload = {
                callid: callid++,
                web_flag: web_flag,
                route: route,
                parms: parms
            };
            client.send("opc_event/", JSON.stringify(payload), 1, false);
        }
    }

    login(window.config.username, window.config.password);

    function get_action() {
        return $('#action').val();
    }

    function get_crane() {
        return $('#crane').val();
    }

    function get_source_area() {
        return $('#source_area').val();
    }

    function get_aim_area() {
        return $('#aim_area').val();
    }

    function get_source_pos() {
        var x = $('#source_x').val();
        var y = $('#source_y').val();
        var z = $('#source_z').val();
        return '' + x + ',' + y + ',' + z;
    }

    function get_aim_pos() {
        var x = $('#aim_x').val();
        var y = $('#aim_y').val();
        var z = $('#aim_z').val();
        return '' + x + ',' + y + ',' + z;
    }

    $('#add_command').click(function (el) {

    });

    var html_data = {
        commands:[]
    };

    var app = new Vue({
            el: '#auto_crane',
            data: html_data,
            methods: {
                do_action: function () {
                    var action = get_action();
                    var crane = get_crane();
                    var source_area = get_source_area();
                    var source_pos = get_source_pos();
                    var aim_area = get_aim_area();
                    var aim_pos = get_aim_pos();
                    var parm = null;
                    if (action == 'from_a_to_b') {


                        parm = {
                            command_id: new Date().getTime() + '',
                            crane: crane,
                            source_area: source_area,
                            source_pos: source_pos,
                            aim_area: aim_area,
                            aim_pos: aim_pos
                        }


                    } else if (action == 'to_b') {
                        parm = {
                            command_id: new Date().getTime() + '',
                            crane: crane,
                            aim_pos: aim_pos
                        }

                    } else if (action == 'from_a_move_to_b') {
                        parm = {
                            command_id: new Date().getTime() + '',
                            crane: crane,
                            source_area: source_area,
                            source_pos: source_pos,
                            aim_area: aim_area,
                            aim_pos: aim_pos
                        }
                    } else if (action == 'put_down') {
                        parm = {
                            command_id: new Date().getTime() + '',
                            crane: crane

                        }

                    } else if (action == 'stop') {
                        parm = {
                            command_id: new Date().getTime() + '',
                            crane: crane
                        }

                    } else if (action == 'auto_10_same_billet') {
                        parm = {
                            command_id: new Date().getTime() + '',

                            aim_area: aim_area
                        }
                    } else if (action == 'auto_10_billet') {
                        parm = {
                            command_id: new Date().getTime() + '',

                            aim_area: aim_area
                        }
                    }
                    liyu_web_api(window.web_flag, action, parm, function (data) {
                        //parm.action = action;
                        html_data.all_objects=data.result.all_object;
                        // alert(data);
                    }, 0);
                    
                }
            }
        })
        ;
});